<?php
//
//	DATABASE CLASS
//


require_once("config.php");


class MySQLDatabase { 
	
	private $dbc;
	public $last_query;
	private $mc_activ;
	private $mysqli_res_exists;
	private $mysql_res_exists;
    private $query_count = 0;
	
	function __construct() {
		$this->open_connection();
		$this->mc_active = get_magic_quotes_gpc();
		$this->mysqli_res_exists = function_exists("mysqli_real_escape_string");
		$this->mysql_res_exists = function_exists("mysql_real_escape_string");
	}
	
	public function open_connection() {
		$this->dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
		if (!$this->dbc) {
			trigger_error ('Could not connect to MySQL: ' . mysqli_connect_error() );
		} else {
		//
		// 	CONNECTED TO DB SUCCESSFULLY
		//
			$db_select = mysqli_select_db($this->dbc, DB_NAME);
			if ( !$db_select ) {
				trigger_error ('Could not select database: ' . mysqli_connect_error() );
			}
		}
	}
	public function the_connecttion() {
	    return $this->dbc;
	}
	public function close_connection() {
		if(isset($this->dbc)) {
			mysqli_close($this->dbc);
			unset($this->dbc);
		}
	}
	
	public function query($sql) {
		$this->last_query = $sql;
		$result = mysqli_query($this->dbc, $sql);
		$this->confirm_query($result);
		return $result;
	}
	
	public function fetch_array( $result_set ) {
		return ( isset($result_set ) &&!empty($result_set) ) ? mysqli_fetch_array ( $result_set, MYSQLI_ASSOC ) : false;
	}
	
	public function num_rows( $result_set ) {
		return mysqli_num_rows ( $result_set );
	}
	
	public function affected_rows() {
		return mysqli_affected_rows ( $this->dbc );
	}
	
	public function insert_id() {
		return mysqli_insert_id ( $this->dbc );
	}
	function total_queries(){
	    return $this->query_count;
	}
	
	
    public function hash_pass($password) {
        $validator = new Validator;
        $password = $validator->escape_value($password);

        $hash = sha1($password); 
        return $hash; 
    }     
	
	private function confirm_query($result) {
		if (!$result && !LIVE ) {
			trigger_error ('Bad Query in ( ' . $this->last_query . ' ) <br /> ' . mysqli_connect_error() );
		}
        $this->query_count ++;
	}
	public static function prepare_search_params($array) {
	    if ( empty($array) ) return false;
	    $sql_string = "";
	    foreach($array as $key => $value ) {
	        if (!empty($value)) 
            switch( $key ) {
                /*
                 * 
                 * 
                 * If searching date ranges, some special things are required:
                 */
                case 'search_date':
                    if ( empty( $from ) || empty( $from ) ) break;
                    $from   = get_weeknum( strtotime($value[1]) );
                    $to     = get_weeknum( strtotime($value[2]) );
                    if ( $value[0] == 'starts_between') {
                        $sql_string .= "AND start_week BETWEEN $from AND $to ";
                    } elseif  ( $value[0] == 'ends_between') {
                        // get total durations, and the subscriptions start week.
                        $allowances = Allowance::find_by_sql( "SELECT *, SUM(total_duration) AS total_duration
                                FROM ".Allowance::get_tablename()." 
                                INNER JOIN ".Subscription::get_tablename()." ON ".Allowance::get_tablename().".subscription_id = ".Subscription::get_tablename().".subscription_id 
                                GROUP BY ".Allowance::get_tablename().".subscription_id
                                " );
                                
                        $id_set = array();
                        foreach($allowances as $allowance) {
                            if( $allowance->total_duration + $allowance->start_week > $from && $allowance->total_duration + $allowance->start_week < $to )
                                $id_set[] = $allowance->subscription_id;
                        }
                        if ( $id_set ) {
                            $ids = implode(',', $id_set);
                            $sql_string .= "AND subscription_id IN ($ids) ";
                        }
                        
                    }
                    break;
                case 'status':
                    switch( $value ) {
                        case "all": $sql_string .= "AND {$key} != 'inactive' "; break;
                        case "everything": break;
                        default: $sql_string .= "AND {$key} = '$value' "; break;
                    }
                    
                    break;
                default:
                    $sql_string .= "AND {$key} LIKE ('%{$value}%') ";
                    break;
            }

	    }
        return $sql_string;
        
	}
}


$db = new MySQLDatabase();
$db->open_connection();

?>